const path = require('path')

const HtmlWebpackPlugin = require('html-webpack-plugin')

const MiniCssExtractPlugin = require('mini-css-extract-plugin')

const {
  CleanWebpackPlugin
} = require('clean-webpack-plugin');

const TerserJSplugin = require('terser-webpack-plugin')

module.exports = (env, argv) => {
  return {
    entry: path.resolve(__dirname, 'src/index.tsx'),
    mode: argv.mode, // development环境才有热更新
    // target: 'web', // webpack5
    output: {
      path: path.resolve(__dirname, 'dist'),
      filename: '[name].[hash].js'
    },
    resolve: {
      extensions: ['.js', '.tsx', '.ts', '.scss', '.sass', '.less', '.css', '.json'],
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
    module: {
      rules: [{
        test: /\.(tsx|ts)$/,
        include: [path.resolve(__dirname, 'src')],
        use: [
          'babel-loader',
          {
            loader: 'ts-loader',
            options: {
              allowTsInNodeModules: true,
            },
          }
        ]
      }, {
        test: /\.css$/,
        use: [
          'style-loader',
          {
            loader: 'css-loader',
            options: {
              import: true,
              url: true
            }
          },
        ]
      }]
    },
    plugins: [
      new CleanWebpackPlugin(),
      new HtmlWebpackPlugin({
        template: './public/index.html'
      }),
      new MiniCssExtractPlugin({
        filename: '[name].[contenthash].css',
      }),
    ],
    optimization: {
      splitChunks: {
        chunks: 'all',
        usedExports: true,
      },
      minimizer: [
        new TerserJSplugin({})
      ]
    },
  }
}